package com.times.util;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;


/**
 * ClassName: ScriptEngineUtils <br/>
 * Function: 
 *
 * @author 
 * @version 2015年6月24日 
 */
public class ScriptEngineUtils {
    
    public static ScriptEngine getJSEngine(){
        return Engine.getInstance();
    }
    
    public static ScriptEngine newInstance(){
		ScriptEngineManager manager = new ScriptEngineManager();
		return manager.getEngineByName("JavaScript");
    }
    
    public static Object processJsEval(String script) throws ScriptException{
        return getJSEngine().eval(script);
    }
    
    /**
     * ClassName: Engine <br/>
     * Function: javascript引擎单例：可以通过调用javascript eval方式计算数学表达式
     *
     * @author 
     * @version 2015年6月25日 CalcEngineUtils
     */
    private static class Engine{
        
        private static ScriptEngine INSTANCE;
        static ScriptEngine getInstance(){
            if(INSTANCE == null){
                ScriptEngineManager manager = new ScriptEngineManager();
                INSTANCE = manager.getEngineByName("JavaScript");
            }
            return INSTANCE;
        }
        
    }
    
    public static void main(String[] args) throws ScriptException {
    	ScriptEngine e = getJSEngine();
    	Bindings bindings = e.getBindings(ScriptContext.ENGINE_SCOPE); 
    	
    	System.out.println(e.eval("a=1,b=2,c=3"));
//    	System.out.println(e.eval("if(true)$a1_1=1;else $a1_1=2;if(1/($a1_1-1)==0)$a1_2=0;else $a1_2=10;$a1_3=4.5;($a1_2+1)*($a1_3-4) ; "));
//    	e.put("i2", 1);
//    	System.out.println(e.eval("$1=(3.2/(i2-7.65));"));
//    	e.put("b", 2.11);
//    	Double c = (Double)e.eval("if(false)c=a+b;else c=5.9;");
//    	System.out.println(c);
//    	System.out.println(e.get("c"));
//    	System.out.println(e.eval("if(3>2) $h1_=(3.2/(i2-7.65));else $h1_=h4;if(3!=0.38){if($h1_<50) $a1_=0.03;else if($h1_>=95) $a1_=(3.2/(i2-7.65));else if($h1_>=80) $a1_=0.06;else if($h1_>=65) $a1_=0.05;else $a1_=0.04;} else $a1_=0;$a1_1=$a1_*(5-1.3);(($a1_+$a1_1)/4)*3"));
//        System.out.println(processJsEval("var x='a';x+'b'"));
//        System.out.println(new BigDecimal("dsd").toString());
    }
    
	
}

